# coding=utf-8

import numpy as np

class SR_Context():
    sr_ID = ''              #本SR角本的标识
    subTaskId = '0'         #并发执行时，一个SR可能被分解，每个子任务的标识

    Max_numY = 1000
    debug = True
    markit = {}             #$动作数据，记录一下当前的numY，numX，即下一表格行、列

    numX = 0
    numY = 0

    data = []
    extdata = []
    moredata = []
    dictdata = {}

    statusY = []
    titlesY = {}
    titlesX = {}
    dictY = {}              #记录纵轴(Y)方向动态Key式条件的key用
    groupby = ''
    df = ''                 #groupby可能要用到的Dataframe
    cursor = ''
    conn = ''
    gb_table = ''           #分组rgoupby所用的表，如果为空，取sql语句中的第一张表
    cur_sql = ''            # 本次计算用的SQL，不一定是角本中设置了的SQL

    py_module = None        # python加载后的module
    grammer = ''            # python源码
    dump = ''               # dump SR_Context
    slaves = []             # slave _src

    finalExprs = []
    gfinalExprs = []
    planStatements = []
    mainStatements = []
    mergeExprs = []

    curY = -1

    _global_context = {}
    parameters = {}

    def __init__(self):
        self._global_context = {}
        self.parameters = {}

        self.sr_ID = ''
        self.subTaskId = '0'

        self.numX = 0
        self.numY = 0

        self.data = []
        self.extdata = []
        self.moredata = []
        self.dictdata = {}

        self.statusY = []
        self.titlesY = {}
        self.titlesX = {}
        self.dictY = {}
        self.groupby = ''
        self.df = ''
        self.cursor = ''
        self.conn = ''
        self.gb_table = ''
        self.cur_sql = ''

        self.py_module = None        # python加载后的module
        self.grammer = ''            # python源码

        self.finalExprs = []
        self.gfinalExprs = []
        self.planStatements = []
        self.mergeExprs = []

        self.curY = -1

        self.debug = True
        self.markit = {}
        self.dump = ''

        self.slaves = []

    def init_datas(self):
        self.statusY = [0] * self.numY
        action = self.get_value('action', '')
        dtype = float
        try:
            if isinstance(eval(action), int):
                dtype=int
        except:
            pass
        self.data = np.zeros([self.numY, self.numX], dtype=dtype)
        self.extdata = np.zeros([self.numY, self.numX], dtype=dtype)

        self.moredata = np.zeros([self.numY, self.numX], dtype='object')
        for i in range(self.numY):
            for j in range(self.numX):
                self.moredata[i,j] = []

        # 角本执行（而不是把SRL翻译成python的过程）阶段生成的数据都应该清理回原始状态
        self.dictdata = {}
        self.dictY = {}
        self.slaves = []


    def set_value(self, name, value):
        self._global_context[name] = value


    def get_value(self, name, defValue=None):
        try:
            return self._global_context[name]
        except KeyError:
            return defValue


    def del_value(self, name, value):
        try:
            del self._global_context[name]
        except KeyError:
            pass


    def getCurData(self, x):
        '''
        c = getCurData(x)
        c[0] = newVal
        '''
        return self.data[self.curY, x:x+1]


    def getCurExtdata(self, x):
        return self.extdata[self.curY, x:x+1]


    def getCurMoredata(self, x):
        return self.moredata[self.curY, x:x+1]


    def appendDictData(self, key, value):
        try:
            arr_ = self.dictdata[key]
        except:
            self.dictdata[key] = []
            arr_ = self.dictdata[key]
        arr_.append(value)


    def getDictData(self, key):
        try:
            arr_ = self.dictdata[key]
        except:
            self.dictdata[key] = []
            arr_ = self.dictdata[key]
        return arr_


    def mergeDictData(self, dictdata):
        if isinstance(dictdata, (list, tuple)):
            for dict_ in dictdata:
                for key, value in dict_:
                    self.appendDictData(key, value)
        else:
            for key, value in dictdata:
                self.appendDictData(key, value)


    def registerSlaves(self, _src):
        self.slaves.append(_src)
